
import angular from 'angular'
import "@yunke/jquery_pagination"
import 'angular-ui'
import '../../../public/js/plugins/select2/select2'
import '../../../public/js/myservice/contract/contract-common'
import myMath from '../../../public/js/myservice/common/my-math'
import config from '../../../public/js/myservice/config'
import util from '@yunke/core/util'
import ui from '@yunke/core/ui'
import authorize from '../../../public/js/myservice/authorize'
import _, { map, chain, assign } from 'lodash'
import 'apiService'
import $ from 'jquery'
import editModalCtrl from './editModalCtrl';

const modalEditProject = require("./balance-inc-edit-project.html");

const apiPrefix = window.G_CONFIG.api_prefix; //api前缀
const sumType = type => products => chain(products)
    .reject(["__type", "delete"])
    .map(({ authorization_type: at, authorization_numeric: an }) => +at === type ? an : 0)
    .reduce((acc, x) => myMath.add(acc, x), 0)
    .value()
angular.module('ContractBalance', ['select2', 'ApiService'])
    .config((apiProvider) => {
        const api = apiProvider.$get();
        api.setApis({
            getDistributionAmount: {
                url: '/api/index.php?r=contract/get-distribution-amount'
            }
        });
    })
    .filter('sumProductAmount2', function () {
        return function (products) {
            return chain(products)
                .reject(["__type", "delete"])
                .reduce((acc, x) => myMath.add(acc, x.amount), 0)
                .value()
        };
    })
    .filter('countSMS2', () => sumType(1))
    .filter('countProject2', () => sumType(0))
    .filter('sumSettlementAverageAmount2', function () {
        return function (products, field) {
            return chain(products)
                .reject(["__type", "delete"])
                .reduce((acc, x) => myMath.add(acc, x[field]), 0)
                .value()
        };
    })
    .filter('contractTypeFilter', function () {
        return function (origin) {
            return {
                '1': '新增',
                '2': '增购',
                '3': '续签'
            }[origin];
        }
    })
    .controller('contractBalanceCtrl', ['$scope', '$routeParams', 'contractCommonService', 'api', '$q', 'isSpecial', 'removeHmS', 'yunkeModal',
        function ($scope, $routeParams, contractCommonService, api, $q, isSpecial, removeHmS, yunkeModal) {
            const service = api.getService();
            $scope.isSpecial = isSpecial;
            $scope.balanceInfo = {};
            $scope.contractFiles = [];
            $scope.projects = [];
            const contractId = $routeParams.id;
            $scope.isDefined = 0;

            //是否区域角色
            authorize.getUserInfoPromise()
                .then((areaRole) => {
                    $scope.areaRole = areaRole;
                });


            // 产品下拉框数据
            $scope.ddlConfigProjectsData = [];
            // 其他产品下拉框数据
            $scope.ddlConfigOtherProjectsData = [];
            //获取产品下拉信息
            contractCommonService.getProducts(function (data) {
                $scope.ddlConfigProjectsData = map(data, d => assign({ id: d.application_id, text: d.application_name }, d))
            });

            //获取其他产品下拉信息
            contractCommonService.getOtherProducts(function (data) {
                $scope.ddlConfigOtherProjectsData = map(data, d => assign({ id: d.application_id, text: d.application_name }, d));
            });

            //获取合同信息
            contractCommonService.getContract(contractId, function (data) {
                $scope.contractBaseInfo = data.contract;
                if (data.contract.contract_property_id === '7f83719a-fce8-11e4-bed8-00155d02c832'
                    || data.contract.contract_property_id === '7f8422d0-fce8-11e4-bed8-00155d02c832'
                    || data.contract.contract_property_id === 'efa353cd-51ca-11e8-a035-00155d02c83e') {
                    //云客签约-直属区域/云客签约-联营区域/云客直销
                    //收入金额汇总 = 签约金额
                    $scope.isDefined = 2;
                }
                $scope.$applyAsync();
            });

            $scope.$watch("contractBaseInfo.contract_property_id", n => {
                if (n !== undefined) {
                    $scope.isSpecialContract = isSpecial(n);
                }
            })
            const loadBalanceProducts = function () {
                const defer = $q.defer();
                //获取产品列表,保存接口
                contractCommonService.getBalanceProducts(contractId, function (data) {
                    $scope.projects = data;
                    $.each($scope.projects, function (i, project) {
                        project.discount_rate = parseFloat(project.discount_rate);
                    });
                    $scope.$applyAsync();
                    defer.resolve();
                });
                return defer.promise;
            };
            loadBalanceProducts();


            /**
             *
             */
            $scope.getDistributionAmount = () => {
                service.getDistributionAmount({ contractId })
                    .then(res => map(res.data.data, (d) => {
                        d.CreatedOn = removeHmS(d.CreatedOn);
                        d.establish_time = removeHmS(d.establish_time);
                        return d;
                    }))
                    .then(data => {
                        $scope.categories = data;
                    })
            };

            $scope.getDistributionAmount();


            //获取结算返款信息
            contractCommonService.getContractBalanceInfo(contractId, function (data) {
                $scope.balanceInfo = data;
                $scope.balanceInfo.balance_rate = myMath.mul($scope.balanceInfo.balance_rate, 100);
                $scope.contractFiles = data.attachement;
                $scope.$applyAsync();
            });

            //基本信息收入金额 - 结算金额 = 返款金额
            $scope.$watch('balanceInfo.balance_amount', function (balanceVal) {
                if (balanceVal !== undefined) {
                    $scope.balanceInfo.back_amount = myMath.sub($scope.contractBaseInfo.sign_amount, balanceVal);
                }
            });


            // 客户下拉框处理
            $scope.ddlConfigBalanceType = {
                allowClear: false,
                data: [],
                placeholder: '结算类型'
            };
            //结算类型 0：标准结算 1：特价结算 2：特批其他
            $scope.ddlConfigBalanceType.data = [
                { id: 0, text: '标准结算' },
                { id: 1, text: '特价结算' },
                { id: 2, text: '特批其他' },
                { id: 3, text: '折上折' },
                { id: 4, text: '合同成交额' }];

            //返款类型下拉框
            $scope.ddlConfigRepaymentType = {
                allowClear: false,
                data: [],
                placeholder: '返款类型'
            };
            //返款类型
            $scope.ddlConfigRepaymentType.data = [
                { id: 0, text: '暂无' },
                { id: 1, text: '现金' },
                { id: 2, text: '转预收' }];

            //返款状态下拉框
            $scope.ddlConfigBalanceStatus = {
                allowClear: false,
                data: [],
                placeholder: '返款状态'
            };
            //返款状态
            $scope.ddlConfigBalanceStatus.data = [
                { id: 0, text: '未返款' },
                { id: 1, text: '已返款' }];

            // 服务机构下拉框处理
            $scope.ddlRepaymentCompany = {
                allowClear: false,
                data: [],
                placeholder: '服务机构'
            };


            //
            $scope.ddlConfigContractType = {
                allowClear: false,
                data: [{
                    id: '1',
                    text: '新增'
                }, {
                    id: '2',
                    text: '增购'
                }, {
                    id: '3',
                    text: '续签'
                }],
                placeholder: '返款状态'
            };

            //
            $scope.ddlConfigSaas = {
                allowClear: false,
                data: [{
                    id: '0',
                    text: '否'
                }, {
                    id: '1',
                    text: '是'
                }],
                placeholder: ''
            };

            contractCommonService.getAgencyCompanyList($scope.balanceInfo.repayment_company, function (data) {
                $scope.ddlRepaymentCompany.data = map(data, d => ({ id: d.company_id, text: d.company_name }));
                $scope.$applyAsync();
            });

            setTimeout(function () {
                $('#fileupload').fileupload({
                    dataType: 'json',
                    url: apiPrefix + "/common/file/upload-document",
                    add(e, data) {
                        // 大小限制
                        if (data.files.length > 0) {
                            if (data.files[0].size > config.uploader.max_file_size) {
                                util.alert('文件大小超出' + config.uploader.max_file_size_text + '，无法上传。');
                                return;
                            }
                        }
                        data.submit();
                        ui.loading('', '正在上传…');
                    },
                    done(e, data) {
                        const res = data.result;
                        if (res.retCode === "0") {
                            const attachement = {
                                __type: 'add',
                                attachement_id: data._time,
                                attachement_name: data.files[0].name,
                                attachement_ext_name: '',
                                attachement_path: res.data.path,
                            };
                            $scope.contractFiles.push(attachement);

                            $scope.$applyAsync();
                            ui.removeLoading();

                            $("#fileupload_error").html("");
                            $("#fileupload_error").hide();
                        } else {
                            ui.removeLoading();
                            $("#fileupload_error").html("上传失败:" + res.errMsg);
                            $("#fileupload_error").show();
                        }
                    },
                    fail(e, data) {
                        $("#fileupload_error").html("上传失败:" + data.errorThrown);
                        $("#fileupload_error").show();
                        ui.removeLoading();
                    },
                    always() {
                        ui.removeLoading();
                    }
                });
            }, 0);
            //附件上传初始化


            /**
             * 删除附件
             * @param data
             * @param id
             */
            $scope.delAttachment = function (item, idx) {
                if (item.__type === 'add') {
                    $scope.contractFiles.splice(idx, 1);
                } else {
                    angular.extend(item, { __type: 'delete' });
                }
                $scope.$applyAsync();
            };
            function saveProduct(needCalc = false) {
                //处理当页面其他处修改之后，该处需要同步修改。 balanceInfo 中的部分信息需要同步到contractBaseInfo 中
                $scope.contractBaseInfo.balance_amount = $scope.balanceInfo.balance_amount;
                $scope.contractBaseInfo.project_numeric = $scope.balanceInfo.project_numeric;
                $scope.contractBaseInfo.back_amount = $scope.balanceInfo.back_amount;
                $scope.contractBaseInfo.balance_remark = $scope.balanceInfo.balance_remark;
                const baseInfo = $scope.contractBaseInfo;
                const projectsInfo = $scope.projects;

                const postData = {
                    //供后台区分是否需要重新计算分摊金额等数字
                    save_type: !needCalc ? "product" : "",
                    contract: baseInfo,
                    product: projectsInfo,
                };

                util.myAjax({
                    url: apiPrefix + "/contract/update-achievement",
                    type: 'POST',
                    context: this,
                    data: postData,
                    success(json) {
                        if (json.retCode === "0") {
                            util.alert('保存成功');
                            loadBalanceProducts()
                                .then(() => $scope.getDistributionAmount());
                        } else {
                            util.alert("保存失败：" + json.errMsg);
                        }
                    }
                })
            }
            function onProductEditShow(oldProd, title) {
                return yunkeModal.open({
                    template: modalEditProject,
                    title,
                    controller: editModalCtrl({
                        oldProd,
                        $scope
                    })
                })
            }
            $scope.onProductAdd = function () {
                return onProductEditShow(null, "新建产品")
                    .promise.then(data => {
                        $scope.projects.push(assign({ __type: 'add', is_standard: '0' }, data));
                        saveProduct(true);
                    })
            }
            $scope.onProductEdit = function (oldProd) {
                const proj = { ...oldProd };
                return onProductEditShow(proj, "修改产品")
                    .promise.then(data => {
                        assign(oldProd, $.extend({ __type: 'update' }, data));
                        saveProduct();
                    })
            }

            $scope.delProject = function (proj) {
                /**
                 * 删除产品
                 */
                util.confirm('确定要删除此产品吗？', {
                    ok() {
                        assign(proj, { __type: 'delete' });
                        saveProduct(true);
                        $scope.$applyAsync();
                    }
                });
            };

            //保存结算信息
            $scope.save = function () {
                const balanceInfo = angular.copy($scope.balanceInfo);
                balanceInfo.balance_rate = myMath.div(balanceInfo.balance_rate, 100);

                balanceInfo.files = $scope.contractFiles;

                balanceInfo.product = $scope.projects;

                //balanceInfo.distribution = _.map($scope.categories, category =>
                //    _.pick(category, 'sign_average_amount', 'settlement_average_amount',
                //        'receivable_average_amount', 'contract_type', 'user_id',
                //        'area_id', 'department_id'));

                const postData = balanceInfo;


                util.myAjax({
                    url: apiPrefix + "/contract/update-contract-account",
                    type: "POST",
                    context: this,
                    data: postData,
                    success(json) {
                        if (json.retCode === "0") {
                            util.alert('保存成功');
                            loadBalanceProducts()
                                .then(() => $scope.getDistributionAmount())
                        } else {
                            util.alert("保存失败：" + json.errMsg);
                        }
                    }
                });
            };

            $scope.saveCategores = function () {
                const categores = {
                    distribution: _.map($scope.categories, category =>
                        _.pick(category, 'sign_average_amount', 'settlement_average_amount',
                            'receivable_average_amount', 'contract_type', 'user_id',
                            'area_id', 'department_id', 'is_saas', 'establish_time')),
                    input_date: $scope.balanceInfo.input_date,
                    contract_id: $scope.balanceInfo.contract_id
                };

                util.myAjax({
                    url: apiPrefix + "/contract/save-distribution-amount",
                    type: "POST",
                    context: this,
                    data: categores,
                    success(json) {
                        if (json.retCode === "0") {
                            $scope.toggleEdit();
                            util.alert('保存成功');
                            loadBalanceProducts()
                                .then(() => $scope.getDistributionAmount())
                        } else {
                            util.alert("保存失败：" + json.errMsg);
                        }
                    }
                });
            };

            $scope.addCategory = category => {
                let categories = $scope.categories || [];
                const add = _.merge({}, _.omit(category, '$$hashKey'), {
                    receivable_average_amount: '0',
                    settlement_average_amount: '0',
                    is_saas: '1',
                    sign_average_amount: '0',
                    amount_id: _.uniqueId()
                });

                const size = _.findIndex(categories, ['amount_id', category.amount_id]) + 1;

                categories = _.flatten([_.take(categories, size), add, _.drop(categories, size)]);

                $scope.categories = categories;
            };

            $scope.isEditMode = false;

            $scope.toggleEdit = () => {
                $scope.isEditMode = !$scope.isEditMode;
            };


            $scope.deleteCategory = category => {
                $scope.categories = _.filter($scope.categories, (cat) => cat.amount_id != category.amount_id);
            };


            /**
             * 签约结算金额校验 两个值相等
             * @returns {boolean}
             */
            $scope.validEq = () => {
                const projects = $scope.projects;

                const categories = $scope.categories;

                if (!_.every($('[name=user_id]'), 'value')) {
                    ui.showErrTip('归属人字段不为空');
                    return false;
                }

                const isEq = (field) => _.sumBy(projects, x => +x[field]) == _.sumBy(categories, x => +x[field]);

                if (!isEq('settlement_average_amount')) {
                    ui.showErrTip('结算业绩分摊金额不等');
                } else if (!isEq('sign_average_amount')) {
                    ui.showErrTip('签约业绩分摊金额不等');
                }

                return isEq('settlement_average_amount') && isEq('sign_average_amount');

            };

            function formatRepo(repo) {
                if (repo.loading) return repo.text;

                return '<div class="clearfix" style="width: 300px;">' +
                    '<div class="clearfix">' +
                    '<div class="col-sm-6">' + repo.user_name + '</div>' +
                    '</div></div>';
            }

            function formatRepoSelection(repo) {
                return repo.text;
            }

            // 合同签约人下拉框处理
            $scope.ddlConfigContractSigner = (category) => {

                const transform = item => ({
                    area_id: item.BUGUID || item.area_id,
                    area_name: item.BUName || item.area_name,
                    department_name: item.DepartmentName || item.department_name,
                    department_id: item.DepartmentId || item.department_id,
                    user_id: item.UserGUID || item.user_id,
                    user_name: item.UserName || item.user_name,
                    text: item.text,
                    id: item.id
                });

                category.ddlConfig = _.merge(category.ddlConfig || {}, {
                    initSelection(element) {
                        $(element).data('select2').updateSelection({
                            text: category.user_name || '',
                            user_id: category.user_id
                        });
                    },
                    allowClear: false,
                    ajax: {
                        url: apiPrefix + "erp-interface/get-users",
                        dataType: 'json',
                        delay: 250,
                        data(term) {
                            return {
                                keyword: term,
                                limit: 10
                            };
                        },
                        results(json) {
                            return {
                                results: _.map(json.data, transform)
                            };
                        },
                        processResults(data) {
                            // parse the results into the format expected by Select2.
                            // since we are using custom formatting functions we do not need to
                            // alter the remote JSON data
                            return {
                                results: _.map(data.items, transform)
                            };
                        },
                        cache: true
                    },
                    escapeMarkup(markup) {
                        return markup;
                    }, // let our custom formatter work
                    minimumInputLength: 1,
                    onchange2(newVal) {
                        category = _.merge(category, transform(newVal));
                        $scope.$applyAsync();
                    },
                    formatResult: formatRepo,
                    formatSelection: formatRepoSelection // omitted for brevity, see the source of this page
                });
                return category.ddlConfig;
            };
        }]);

